import React, { useEffect, useState, FC } from 'react'
import { useNavigate } from 'react-router-dom'
import styles from './index.module.less'
import { Form, Input, Button, Toast, Radio, Checkbox } from 'antd-mobile'
import { EyeInvisibleOutline, EyeOutline } from 'antd-mobile-icons'
import Captcha from '@/comopnents/Captcha'
import { userRegister } from '@/utils/my/register'
import { uploadAvatar } from '@/utils/my/updateuserinfo'
import Loading from '@/comopnents/loading'


interface formType {
  username: string
  password: string
  phone: string
  nickname: string
  captcha: string
  icon: string
}


export default function Register() {

  const navigate = useNavigate()

  const [captchaVal, setCaptchaVal] = useState<string>()

  // 密码可见
  const [visible, setVisible] = useState<boolean>(false)
  // 单选框的选中状态
  const [isSelect, setIsSelect] = useState<boolean>(true)
  // 修改后的图片地址
  const [fileUrl, setFileUrl] = useState<string>()
  // 是否点击了更新
  const [isLoading, setIsLoading] = useState<boolean>(false)


  // 注册按钮
  const registerBtnClick = (val: formType) => {
    if (isSelect) {
      val.icon = fileUrl ? fileUrl : ""
      console.log(captchaVal)
      if (val.captcha === captchaVal) {
        userJoin(val)
        setIsLoading(true)
      } else {
        Toast.show({
          icon: 'fail',
          content: '验证码错误',
        })
      }
    } else {
      Toast.show({
        icon: 'fail',
        content: '请同意注册协议',
      })
    }

  }

  // 用户注册请求
  const userJoin = async (data: object) => {
    let res: resType = await userRegister(data)
    if (res.code === 20000) {
      Toast.show({
        icon: 'loading',
        content: <CountDownText />,
        duration: 3000,
        afterClose: () => {
          navigate('/my/login')
          setIsLoading(false)
        }
      })
      return
    }
    Toast.show({
      icon: 'fail',
      content: res.message,
      duration: 1000,
      afterClose: () => setIsLoading(false)
    })
  }

  // 进入登录页倒计时
  const CountDownText: FC = () => {
    const [count, setCount] = useState(3)
    useEffect(() => {
      const interval = window.setInterval(() => {
        setCount(x => {
          if (x > 1) {
            return x - 1
          } else {
            return x
          }
        })
      }, 1000)
      return () => {
        window.clearInterval(interval)
      }
    }, [])
    return <div className={styles.infoJump}>注册成功,将在{count}秒后跳转到登录页</div>
  }

  // 上传头像
  const updateImg = (file: any) => {
    const files = file.target.files
    if (!files.length) return
    // 上传文件 
    let formData = new FormData()
    formData.append('file', files[0], files[0].name)
    upLoadImg(formData)
  }

  // 上传头像的请求
  const upLoadImg = async (data: any) => {
    let res: resType = await uploadAvatar(data)
    if (res.code === 20000) {
      setFileUrl(res.data.fileUrl)
      return
    }
  }

  useEffect(() => {
    if (localStorage.getItem('token')) {
      navigate('/my')
    }
  }, [])
  return (
    <div className={styles.registerBox}>
      {/* 头像 */}
      <div className={styles.txBox}>
        <img className={styles.tx} src={fileUrl ? fileUrl : require('@/static/logo.png')} alt="logo" />
        <input type="file" className={styles.ImgInput} name="file" onChange={updateImg} />
      </div>
      {/* <div>表单</div> */}
      <Form className={styles.formBox} requiredMarkStyle='text-required' onFinish={registerBtnClick}>

        <Form.Item className={styles.info} name='phone' rules={[{ required: true, message: '请输入手机号' }, { pattern: /^1(3[0-9]|4[01456879]|5[0-3,5-9]|6[2567]|7[0-8]|8[0-9]|9[0-3,5-9])\d{8}$/, message: '请输入正确的手机号' }]} >
          <Input type="number" clearable placeholder='请输入手机号' />
        </Form.Item>

        <Form.Item className={styles.info} name='password' rules={[{ required: true, message: '请输入登录密码' }, { min: 5, max: 12, message: '密码长度应为5~12位之间' }]} extra={
          <div className={styles.eye}>
            {!visible ? (
              <EyeInvisibleOutline onClick={() => setVisible(true)} />
            ) : (
              <EyeOutline onClick={() => setVisible(false)} />
            )}
          </div>
        } >
          <Input clearable type={visible ? 'text' : 'password'} placeholder='请输入登录密码' />
        </Form.Item>

        <Form.Item className={styles.info} name='username' rules={[{ required: true, message: '请输入用户名' }, { min: 2, max: 12, message: '用户名长度应为2~12位之间' }]} >
          <Input clearable placeholder='请输入用户名,该用户名将用于账户登录' />
        </Form.Item>

        <Form.Item className={styles.info} name='nickname' rules={[{ required: true, message: '请输入昵称' }, { min: 2, max: 12, message: '昵称长度应为2~12位之间' }]} >
          <Input clearable placeholder='请输入昵称' />
        </Form.Item>

        <Form.Item className={styles.info} name='captcha' rules={[{ required: true, message: '请输入验证码' }, { len: 4, message: '验证码长度为4位' }]}>
          <Input clearable placeholder='请输入验证码' />
        </Form.Item>


        <div className={styles.yzm}>
          <Captcha captchaVal={captchaVal} getTrueCaptcha={(val?: string) => setCaptchaVal(val)}></Captcha>
        </div>


        <Button className={styles.submit} shape='rounded' type='submit' color='primary' size='large'>
          {
            isLoading ? <Loading></Loading> : <>注册</>
          }
        </Button>
      </Form>

      <div className={styles.radioBox}>
        <Checkbox
          defaultChecked
          style={{
            '--icon-size': '18px',
            '--font-size': '14px',
            '--gap': '6px',
          }}
          onChange={(val) => setIsSelect(val)}
        >
          同意《协议》
        </Checkbox>
      </div>
    </div>
  )
}
